<template>
    <div class="warehouse-container">
        <div class="filter-container">
            <el-input v-model="listQuery.mid_table_remark_003_like" placeholder="房源名称" clearable
                class="filter-item input-item" style="width: 200px;" @clear="handleFilter"
                @keyup.enter.native="handleFilter" />
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
        </div>

        <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
            style="width: 100%;">
            <el-table-column label="ID" prop="id" align="center" width="80" :class-name="getSortClass('id')">
                <template slot-scope="{row}">
                    <span>{{ row.id_public_middle_table }}</span>
                </template>
            </el-table-column>
            <el-table-column label="预览图" align="center">
                <template slot-scope="{row}">
                    <el-image :src="row.mid_table_remark_002"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="房源名称" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.mid_table_remark_003 || '-' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="房源类型" align="center">
                <template slot-scope="{row}">
                    <span>{{ houseType[row.mid_table_remark_004] || '-' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="使用面积" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.mid_table_remark_006 ? `${row.mid_table_remark_006}m²` : '-' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="使用面积" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.mid_table_remark_008 ? `${row.mid_table_remark_008}元` : '-' }}</span>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-show="total > 0" background :page.sync="currentPage" @current-change="getPageList"
            :page-size="pageSize" :total="total">
        </el-pagination>

    </div>
</template>
  
<script>
import { getWarehouseList } from '@/api/warehouse'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import areaData from '@/utils/area.json'

export default {
    name: 'Warehouse',
    components: { Pagination },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                published: 'success',
                draft: 'info',
                deleted: 'danger'
            }
            return statusMap[status]
        }
    },
    data() {
        const validatePhone = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入手机号'))
            } else if (!(/^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/.test(value))) {
                this.temp.agent_phone = ''
                callback(new Error('手机号码格式不正确'))
            } else {
                callback()
            }
        }

        return {
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            currentPage: 0,
            houseType: {
                1001: "整租",
                1002: "合租",
                1003: "公寓",
                1004: "商铺",
                1005: "新房",
                1006: "二手房"
            },
            listQuery: {
                invoke_method: 'public_load_middle_table_list',
                pre_db_para_middle_table_name: 'public_middle_table_lite_mod_interview_exam',
                type_middle_app: '14001',
                type_inner_app: '3003',
                is_online: '0',
                pre_db_para_begin_idx: '0',
                pre_db_para_length_4_list: '4',
                mid_table_remark_003_like: ''
            },
            temp: {
                id_public_agent_info: null,
                agent_name: null,
                contact_name: null,
                agent_phone: null,
                account_user: null,
                account_pwd: null,
                agent_province: null,
                agent_city: null,
                agent_country: null,
                agent_addr: null,
                is_online: 0,
                agent_type_4_user: 10
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: '编辑',
                create: '新增'
            },
            dialogPvVisible: false,
            rules: {
                agent_name: [
                    { required: true, message: '请输入供应商名称', trigger: 'blur' }
                ],
                contact_name: [
                    { required: true, message: '请输入联系人名称', trigger: 'blur' }
                ],
                agent_phone: [
                    { required: true, message: '请输入联系人电话', trigger: 'blur' },
                    { validator: validatePhone, trigger: 'blur' }
                ],
                account_user: [
                    { required: true, message: '请输入登录账户', trigger: 'blur' }
                ],
                agentPassword: [
                    { required: true, message: '请输入登录密码', trigger: 'blur' }
                ],
                agent_province: [
                    { required: true, message: '请选择所在省份', trigger: 'blur' }
                ],
                agent_city: [
                    { required: true, message: '请选择所在市(区)', trigger: 'blur' }
                ],
                agent_country: [
                    { required: true, message: '请选择所在县(区)', trigger: 'blur' }
                ],
                agent_addr: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' }
                ]
            },
            downloadLoading: false,
            /** 省份数据 */
            provinceData: [],
            provinceValue: '',
            /** 市数据 */
            citiesData: [],
            citiesValue: '',
            /** 区数据 */
            cityAreaData: [],
            cityAreaValue: ''
        }
    },
    created() {
        areaData.forEach(item => {
            this.provinceData.push({
                value: item.code,
                label: item.name,
                children: item.children
            })
        })
    },
    mounted() {
        // https://115292928app8001.downline.cn/duzikai_api_mgr_public_middle_table?invoke_method=public_load_middle_table_list&pre_db_para_middle_table_name=public_middle_table_lite_mod_interview_exam&type_middle_app=14001&type_inner_app=3003&is_online=0&pre_db_para_begin_idx=0&pre_db_para_length_4_list=10&mid_table_remark_003_like=
        this.getList()
    },
    methods: {
        /*
        * 获取页面数据
        * */
        getList() {
            this.listLoading = true
            // console.log(this.Qs);
            console.log(this.listQuery)
            getWarehouseList(this.listQuery).then(response => {
                console.log(response)
                this.list = response.page_content
                this.total = response.result_num

                // Just to simulate the time of the request
                setTimeout(() => {
                    this.listLoading = false
                }, 0.5 * 1000)
            })
        },
        /*
        * 点击分页进行查询
        * */
        getPageList(val) {
            this.listQuery.pre_db_para_begin_idx = (val - 1) * this.listQuery.pre_db_para_length_4_list
            this.getList()
        },
        /*
        * 查询数据
        * */
        handleFilter() {
            this.listQuery.pre_db_para_begin_idx = 0
            this.getList()
        },
        resetTemp() {
            this.temp = {
                id_public_agent_info: null,
                agent_name: null,
                contact_name: null,
                agent_phone: null,
                account_user: null,
                account_pwd: null,
                agent_province: null,
                agent_city: null,
                agent_country: null,
                agent_addr: null,
                is_online: 0,
                agent_type_4_user: 10
            }
        },
        /*
        * 新增数据
        * */
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    console.log(this.temp)
                    this.updateData()
                    /*warehouseList(this.Qs.stringify({
                      invoke_method: 'public_page_4m_insert_empty_agent',
                      empower_code: 123,
                      id_public_agent_info: this.list[0].id_public_agent_info,
                      auto_inset_relation: true
                    })).then(response => {
                      this.temp.id_public_agent_info = response.page_content.id_public_agent_info
                      this.updateData()
                    })*/
                }
            })
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row) // copy obj
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            const agentUpdateLoading = this.$loading({
                lock: true,
                text: '提交中，请稍后',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, .7)'
            });

            warehouseList(this.Qs.stringify({
                invoke_method: 'public_page_4m_insert_or_upd_agent_info',
                pre_db_para_id_public_agent_info: this.temp.id_public_agent_info,
                agent_name: this.temp.agent_name,
                contact_name: this.temp.contact_name,
                agent_phone: this.temp.agent_phone,
                account_user: this.temp.account_user,
                account_pwd: this.temp.account_pwd,
                agent_province: this.temp.agent_province,
                agent_city: this.temp.agent_city,
                agent_country: this.temp.agent_country,
                agent_addr: this.temp.agent_addr,
                is_online: 0,
                agent_type_4_use: 10
            })).then(response => {
                this.$notify({
                    title: 'Success',
                    message: '新增成功',
                    type: 'success',
                    duration: 2000
                })
                agentUpdateLoading && agentUpdateLoading.close()
                this.dialogFormVisible = false
                if (this.dialogStatus === 'creat') {
                    this.$notify({
                        title: 'Success',
                        message: '新增成功',
                        type: 'success',
                        duration: 2000
                    })
                } else {
                    this.$notify({
                        title: 'Success',
                        message: '编辑成功',
                        type: 'success',
                        duration: 2000
                    })
                }
                this.getList()
            }).catch(() => {
                agentUpdateLoading && agentUpdateLoading.close()
            })
        },
        handleDelete(row, index) {
            console.log(row)
            this.$confirm('您确定要删除该仓库数据吗?', '提示', {
                type: 'warning'
            }).then(() => {
                warehouseList(this.Qs.stringify({
                    invoke_method: 'public_page_4m_insert_or_upd_agent_info',
                    pre_db_para_id_public_agent_info: row.id_public_agent_info,
                    is_online: 111,
                })).then(() => {
                    this.$notify({
                        title: 'Success',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                    if ((this.total - 1) == (this.currentPage - 1) * this.listQuery.pre_db_para_length_4_list) {
                        if (this.currentPage - 2 > 0 || this.currentPage - 2 == 0) {
                            this.listQuery.pre_db_para_begin_idx = (this.currentPage - 2) * this.listQuery.pre_db_para_length_4_list
                        }
                    }
                    this.getList()
                })
            }).catch(() => {
                this.getList()
            })
        },

        /*
        * 商品注册
        * */
        handleRegisterGoods(item) {
            this.$router.push({ name: 'FindGoods', query: { agent_id: item.id_public_agent_info } })
        },

        // 查看合作店铺
        handleCheckShop(item) {
            this.$router.push({ name: 'BindShop', query: { agent_id: item.id_public_agent_info } })
        },

        formatJson(filterVal) {
            return this.list.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        getSortClass: function (key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        },

        /** 选择所在省份 */
        selectProvince(val) {
            if (val) {
                this.citiesValue = val.children[0].name
                this.cityAreaValue = val.children[0].children[0].name
                this.temp.agent_province = val.label
                this.temp.agent_city = val.children[0].name
                this.temp.agent_country = val.children[0].children[0].name
                this.citiesData = []
                this.cityAreaData = []
                val.children.forEach(item => {
                    this.citiesData.push({
                        label: item.name,
                        value: item.code,
                        children: item.children
                    })

                    item.children.forEach(ele => {
                        this.cityAreaData.push({
                            label: ele.name,
                            value: ele.code
                        })
                    })
                })
            }
        },
        /** 选择所在市 */
        selectCity(val) {
            if (val) {
                this.cityAreaValue = val.children[0].name
                this.temp.agent_city = val.label
                this.temp.agent_country = val.children[0].name
                this.cityAreaData = []
                val.children.forEach(item => {
                    this.cityAreaData.push({
                        label: item.name,
                        value: item.code
                    })
                })
            }
        },
        /** 选择所在区 */
        selectCityArea(val) {
            console.log(val)
            this.cityAreaValue = val.label
            this.temp.agent_country = val.label
        },
        /** 清空选择数据 */
        clearData(type) {
            switch (type) {
                case 1001:
                    this.provinceValue = ''
                    this.citiesValue = ''
                    this.cityAreaValue = ''
                    this.temp.agent_province = null
                    this.temp.agent_city = null
                    this.temp.agent_country = null
                    break
                case 1002:
                    this.citiesValue = ''
                    this.cityAreaValue = ''
                    this.temp.agent_city = null
                    this.temp.agent_country = null
                    break
                case 1003:
                    this.cityAreaValue = ''
                    this.temp.agent_country = null
                    break
            }
        }
    },
    computed: {
        pageSize() {
            try {
                return Number(this.listQuery.pre_db_para_length_4_list)
            } catch (error) {
                return 10;
            }
        }
    }
}
</script>
  
<style lang="scss" scoped>
.warehouse-container {
    margin: 24px 24px 0;
    padding: 16px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 8px;

    .filter-container {
        .el-button {
            background-color: #ec4040;
            border-color: #ec4040;
        }
    }

    .el-table {
        .el-button {
            background-color: #fff;
            color: #ec4040;
            border: none;
            padding: 0;
            font-size: 14px;
        }
    }

    .page-content {
        min-height: 500px;
    }

    .grid {
        position: relative;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    }

    .input-item {
        margin-right: 24px;
    }
}
</style>
<style>
.el-input__inner {
    line-height: 1px !important;
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #ec4040;
}
</style>
  